package io.renren.modules.substation.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import io.netty.util.internal.StringUtil;
import io.renren.common.utils.StringUtils;
import io.renren.modules.substation.entity.*;
import io.renren.modules.substation.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 设备监测信息实时表
 *
 * @author yzx
 * @email sunlightcs@gmail.com
 * @date 2020-06-20 11:20:38
 */
@RestController
@RequestMapping("substation/tbusidevmonitorinfo")
public class TBusiDevMonitorInfoController {
    private static Logger logger = LoggerFactory.getLogger(TInfoBackupConfigController.class);

    @Autowired
    private TBusiDevMonitorInfoService tBusiDevMonitorInfoService;
    @Autowired
    private TBusiDevMonitorHisService tBusiDevMonitorHisService;
    @Autowired
    private TBaseDictInfoService tBaseDictInfoService;
    @Autowired
    private TInfoDevInfoService tInfoDevInfoService;
    @Autowired
    private TInfoAreaInfoService tInfoAreaInfoService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("substation:tbusidevmonitorinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tBusiDevMonitorInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("substation:tbusidevmonitorinfo:info")
    public R info(@PathVariable("id") Long id){
		TBusiDevMonitorInfoEntity tBusiDevMonitorInfo = tBusiDevMonitorInfoService.getById(id);

        return R.ok().put("tBusiDevMonitorInfo", tBusiDevMonitorInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("substation:tbusidevmonitorinfo:save")
    public R save(@RequestBody TBusiDevMonitorInfoEntity tBusiDevMonitorInfo){
		tBusiDevMonitorInfoService.save(tBusiDevMonitorInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("substation:tbusidevmonitorinfo:update")
    public R update(@RequestBody TBusiDevMonitorInfoEntity tBusiDevMonitorInfo){
		tBusiDevMonitorInfoService.updateById(tBusiDevMonitorInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("substation:tbusidevmonitorinfo:delete")
    public R delete(@RequestBody Long[] ids){
		tBusiDevMonitorInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 获取配电房终端设备测量信息
     */
    @RequestMapping("/getDevMeasureBySta")
    @RequiresPermissions("substation:tbusidevmonitorinfo:getDevMeasureBySta")
    public R getDevMeasureBySta(@RequestParam String stationId){
        Map<String, Object> data = new HashMap<>();
        int staMeasureCnt = 0, staNormalCnt = 0;
        Map<String, Object> param = new HashMap<>();
        param.put("stationId", stationId);
        staMeasureCnt = tBusiDevMonitorInfoService.countAllMeasureBySta(param);
        staNormalCnt = tBusiDevMonitorInfoService.countNormalMeasureBySta(param);
        data.put("staMeasureCnt", staMeasureCnt);
        data.put("staNormalCnt", staNormalCnt);
        return R.ok().put("data", data);
    }

    /**
     * 获取普通区域终端设备测量信息
     */
    @RequestMapping("/getDevMeasureByArea")
    @RequiresPermissions("substation:tbusidevmonitorinfo:getDevMeasureByArea")
    public R getDevMeasureByArea(@RequestParam String stationId){
        Map<String, Object> data = new HashMap<>();
        int staMeasureCnt = 0, staNormalCnt = 0;
        Long areaId = Long.parseLong(stationId);
        String subAreaStr = tInfoAreaInfoService.getSubAreaList(areaId);
        staMeasureCnt = tBusiDevMonitorInfoService.countAllMeasureByArea(subAreaStr);
        staNormalCnt = tBusiDevMonitorInfoService.countNormalMeasureByArea(subAreaStr);
        data.put("staMeasureCnt", staMeasureCnt);
        data.put("staNormalCnt", staNormalCnt);
        return R.ok().put("data", data);
    }

    public String getAddTime(String startTime,int index){
        try {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
            Date sdate = fmt.parse(startTime);
            calendar.setTime(sdate);
            calendar.add(Calendar.SECOND,index);
            String date = fmt.format(calendar.getTime());
            logger.debug("new date:"+date);
            return date;
        } catch (ParseException e) {
            //e.printStackTrace();
            logger.debug("parse startTime error :"+ startTime);
            return startTime;
        }
    }

    /**
     * 获取设备监测数据
     */
    @RequestMapping("/getDevDataByDev")
    @RequiresPermissions("substation:tbusidevmonitorinfo:getDevDataByDev")
    public R getDevDataByDev(@RequestParam String devId){
        String PD_maxValue = "", infrared_maxValue = "", humidity_value = "", temperature_value = "";
        String PD = "", infrared = "", humidity = "", temperature = "", light = "", noise = "";
        List<TBaseDictInfoEntity> dic_List = tBaseDictInfoService.queryByDictKey("PD_INTERVAL");
        int query_interval = 15;
        if(dic_List != null && dic_List.size()>0) {
            query_interval = Integer.parseInt(dic_List.get(0).getDictValue());
        }
        query_interval = 0 - query_interval * 60;
        logger.debug("query_interval:"+query_interval);

        TInfoDevInfoEntity dev = tInfoDevInfoService.getById(devId);
        String devCode = "";
        if (dev.getDevCode() != null)
            devCode = dev.getDevCode();

        TBusiDevMonitorInfoEntity queryTmp= new TBusiDevMonitorInfoEntity();
        queryTmp.setDevCode(devCode);
        queryTmp.setVariableKind("00");

        List<TBusiDevMonitorInfoEntity> queryList = tBusiDevMonitorInfoService.queryMonitorByCondition(queryTmp);

        PartialDischargeInfo tmp= new PartialDischargeInfo();
        tmp.setDtlList(queryList);
        tmp.init();

        for(TBusiDevMonitorInfoEntity q : queryList){
            TBusiDevReportInfo rtmp = new TBusiDevReportInfo();
            rtmp.setVarKind(q.getVariableKind());
            rtmp.setVarCode(q.getVariableCode());
            rtmp.setDevCode(q.getDevCode());
            String endtime =q.getMonitorTime();
            String startime = getAddTime(endtime,query_interval);
            rtmp.setStartDate(startime);
            rtmp.setEndDate(endtime);

            if(q.getVariableDesc().contains(PartialDischargeInfo.PDINFO)){
                PD = q.getVariableStatus().equals("0") ? "正常" : "告警";
                TBusiDevReportInfo reportInfo=tBusiDevMonitorHisService.queryVarForReport(rtmp);
                //局放状态正常； 峰值 ，均值，频次，
                PD_maxValue = reportInfo.getMaxVarValue();
            }else if(q.getVariableDesc().contains(PartialDischargeInfo.INFRAREDINFO)){
                infrared = q.getVariableStatus().equals("0") ? "正常" : "告警";
                TBusiDevReportInfo reportInfo= tBusiDevMonitorHisService.queryVarForReport(rtmp);
                infrared_maxValue = reportInfo.getMaxVarValue();
            } else if(q.getVariableDesc().contains(PartialDischargeInfo.HUMIDITY)){
                humidity = q.getVariableStatus().equals("0") ? "正常" : "告警";
                humidity_value = q.getVariableValue();
            } else if(q.getVariableDesc().contains(PartialDischargeInfo.TEMPERATURE)){
                temperature = q.getVariableStatus().equals("0") ? "正常" : "告警";
                temperature_value = q.getVariableValue();
            } else if(q.getVariableDesc().contains(PartialDischargeInfo.PICTURESINFO)){
                light = q.getVariableStatus().equals("0") ? "正常" : "告警";
            } else if(q.getVariableDesc().contains(PartialDischargeInfo.NOISEINFO)){
                noise = q.getVariableStatus().equals("0") ? "正常" : "告警";
            }
        }

        Map<String, Object> devData = new HashMap<>();
        devData.put("PD", PD);
        devData.put("PD_maxValue", PD_maxValue);
        devData.put("infrared", infrared);
        devData.put("infrared_maxValue", infrared_maxValue);
        devData.put("humidity", humidity);
        devData.put("humidity_value", humidity_value);
        devData.put("temperature", temperature);
        devData.put("temperature_value", temperature_value);
        devData.put("light", light);
        devData.put("noise", noise);
        return R.ok().put("devData", devData);
    }

    /**
     * 获取配电房标注信息
     */
    @RequestMapping("/getImgTagList")
    @RequiresPermissions("substation:tbusidevmonitorinfo:getImgTagList")
    public R getImgTagList(@RequestParam Long areaId){
        TInfoAreaInfoEntity areaTag = tInfoAreaInfoService.getById(areaId);
        String[] tagInfos = {}, tagPositions = {};
        if (areaTag != null && !StringUtil.isNullOrEmpty(areaTag.getTagInfo())){
            tagInfos = areaTag.getTagInfo().split("&&");
        }
        if (areaTag != null && !StringUtil.isNullOrEmpty(areaTag.getTagPosition())){
            tagPositions = areaTag.getTagPosition().split("&&");
        }
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> obj = new HashMap<>();
        for (int i = 0; i < tagInfos.length; i++) {
            obj = new HashMap<>();
            obj.put("name", tagInfos[i]);
            String[] position = tagPositions[i].split(",");
            obj.put("top", position[0]);
            obj.put("left", position[1]);
            if (position.length > 2)
                obj.put("color", position[2]);
            list.add(obj);
        }
        return R.ok().put("data", list);
    }
}
